<?php
require_once '../includes/functions.php';
check_login();

header('Content-Type: application/json');

// 获取POST数据
$data = json_decode(file_get_contents('php://input'), true);
$template_name = $data['template'] ?? '';
$content = $data['content'] ?? '';

if (empty($template_name) || !isset($content)) {
    http_response_code(400);
    echo json_encode(['error' => '参数错误']);
    exit;
}

// 验证模板名称格式
if (!preg_match('/^[a-zA-Z0-9-_]+$/', $template_name)) {
    http_response_code(400);
    echo json_encode(['error' => '无效的模板名称']);
    exit;
}

$template_path = get_template_path($template_name);
$html_file = $template_path . '/index.html';

// 检查模板是否存在
if (!file_exists($template_path) || !is_dir($template_path)) {
    http_response_code(404);
    echo json_encode(['error' => '模板不存在']);
    exit;
}

// 保存模板内容
if (file_put_contents($html_file, $content) === false) {
    http_response_code(500);
    echo json_encode(['error' => '保存模板失败']);
    exit;
}

echo json_encode(['success' => true, 'message' => '模板保存成功']);
